package com.example.projectmanagement.service.study;

import com.example.projectmanagement.model.study.StudyPointsTransaction;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.StudyPointsTransactionRepository;
import com.example.projectmanagement.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudyPointsService {

    @Autowired
    private StudyPointsTransactionRepository pointsRepository;
    
    @Autowired
    private UserRepository userRepository;

    /**
     * 为用户添加积分
     */
    @Transactional
    public StudyPointsTransaction addPoints(User user, Integer points, String transactionType, String description, Long referenceId) {
        // 创建积分交易记录
        StudyPointsTransaction transaction = new StudyPointsTransaction();
        transaction.setUser(user);
        transaction.setPoints(points);
        transaction.setTransactionType(transactionType);
        transaction.setDescription(description);
        transaction.setReferenceId(referenceId);
        transaction.setTransactionTime(LocalDateTime.now());
        
        StudyPointsTransaction savedTransaction = pointsRepository.save(transaction);
        
        // 更新用户总积分
        user.setStudyPoints(user.getStudyPoints() != null ? user.getStudyPoints() + points : points);
        userRepository.save(user);
        
        return savedTransaction;
    }

    /**
     * 获取用户积分交易记录（分页）
     */
    public Page<StudyPointsTransaction> getUserPointsTransactions(User user, Pageable pageable) {
        return pointsRepository.findByUserIdWithUser(user.getId(), pageable);
    }

    /**
     * 获取用户积分交易记录（不分页）
     */
    public List<StudyPointsTransaction> getUserPointsTransactions(User user) {
        return pointsRepository.findByUserAndTransactionTimeBetween(user, 
            LocalDateTime.now().minusDays(7), LocalDateTime.now());
    }

    /**
     * 获取用户总积分
     */
    public Integer getUserTotalPoints(User user) {
        return pointsRepository.getTotalPointsByUserId(user.getId());
    }

    /**
     * 获取用户最近的积分交易记录
     */
    public Page<StudyPointsTransaction> getRecentTransactions(User user, Pageable pageable) {
        return pointsRepository.findByUserIdWithUser(user.getId(), pageable);
    }

    /**
     * 用户观看视频获得积分
     */
    @Transactional
    public StudyPointsTransaction earnPointsForWatchingVideo(User user, Integer minutesWatched, Long lessonId) {
        // 每分钟获得1积分，最多10积分
        int points = Math.min(minutesWatched, 10);
        return addPoints(user, points, "WATCH_VIDEO", 
            "观看视频获得积分 (" + minutesWatched + "分钟)", lessonId);
    }

    /**
     * 用户完成课程获得积分
     */
    @Transactional
    public StudyPointsTransaction earnPointsForCompletingCourse(User user, Long courseId) {
        return addPoints(user, 50, "COMPLETE_COURSE", "完成课程获得积分", courseId);
    }

    /**
     * 用户提问获得积分
     */
    @Transactional
    public StudyPointsTransaction earnPointsForAskingQuestion(User user, Long questionId) {
        return addPoints(user, 5, "ASK_QUESTION", "提问获得积分", questionId);
    }

    /**
     * 用户回答被采纳获得积分
     */
    @Transactional
    public StudyPointsTransaction earnPointsForAcceptedAnswer(User user, Long answerId) {
        return addPoints(user, 20, "ACCEPTED_ANSWER", "回答被采纳获得积分", answerId);
    }

    /**
     * 用户每日签到获得积分
     */
    @Transactional
    public StudyPointsTransaction earnPointsForDailyCheckIn(User user) {
        // 连续签到天数递增积分，第1天5分，第7天20分
        // 这里简化处理，固定给5分
        return addPoints(user, 5, "DAILY_CHECKIN", "每日签到获得积分", null);
    }
}